package my.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import my.springboot3.dto.PageDto;
import my.springboot3.dto.entity.Article;
import my.springboot3.dto.entity.Category;
import my.springboot3.mapper.ArticleMapper;
import my.springboot3.service.ArticleService;
import my.springboot3.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 图片保存文件夹路径
     */
    @Value("${app.upload.directory}")
    private String uploadPath;


    @Override
    public PageDto<Article> ListAll(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 分页查询文章,添加条件
        Page<Article> articlePage = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> qw = new QueryWrapper<>();
        if (categoryId != null) {
            qw.eq("category_id", categoryId);
        }
        if (state != null) {
            qw.eq("state", state.trim());
        }
        // 执行分页查询并提取结果
        IPage<Article> articleIPage = articleMapper.selectPage(articlePage, qw);
        return new PageDto<>(articleIPage.getTotal(), articleIPage.getRecords());


    }

    /**
     * 上传图片
     * @return 用户id+文件名name,不包括文件夹前缀
     */
    @Override
    public String upload(MultipartFile file) {
        // 获取文件名
        String originalName = file.getOriginalFilename();
        String name = ThreadLocalUtil.get().toString();
        String path = uploadPath + name + originalName;
        try {
            // 保存图片文件到本地
            java.io.File uploader = new java.io.File(uploadPath);
            file.transferTo(new java.io.File(path));
            // 返回图片名字,不包括文件夹前缀
            return name + originalName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public Category findById(Integer id) {
        return null;
    }

    @Override
    public void update(Article article) {

    }

    @Override
    public void deleteById(Integer id) {
        articleMapper.deleteById(id);
    }

    @Override
    public void add(Article article) {
        // 添加文章
        // 补充文章作者
        Integer id = (Integer) ThreadLocalUtil.get();
        article.setCreateUser(id);
        articleMapper.add(article);
    }
}
